<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/9 11:13
 * Desc:
 */
trait Trait_Api_Spot
{
    /**
     * 门票套餐信息
     * @param $params
     * @return array
     * @throws Exception
     */
    public function suit_info($params = array())
    {
        $suit_id = Arr::get($params, 'suit_id');

        // 请求来源于预订页面时返回套餐预订信息
        $source = Arr::get($params, 'source', '');
        if($source == 'book') {
            return Model_Api_V2_Spot::book_suit_info($suit_id);
        }

        $suit_info           = Model_Spot_Suit::suit_info($suit_id);
        $suit_info['litpic'] = $this->img_url($suit_info['litpic']);
        if (empty($suit_info)) {
            throw new Exception(__("未获取到门票套餐信息"));
        }

        $type = Model_Api_V2_Spot::get_ticket_type($suit_info['tickettypeid']);

        $suit_info['ticket_type_name']       = !empty($type) ? $type['kindname'] : '';
        $suit_info['description']             = Model_Api_V2_Xcx::filter_content($suit_info['description']);
        $refund_class                         = Service_Refund_Rule_Factory::get_instance(self::TYPE_ID);
        $suit_info['refund_rule']             = $refund_class->get_format_refund_rule($suit_id);
        $suit_info['refund_restriction_name'] = $refund_class->get_refund_restriction_name($suit_info['refund_restriction']);
        $suit_info['people_rule']             = Model_Spot_Ticket_People_Rule::get_ticket_people_rule($suit_id);

        unset($suit_info['addtime']);
        unset($suit_info['modtime']);
        unset($suit_info['displayorder']);
        unset($suit_info['eticketType']);
        unset($suit_info['eticketsmssign']);
        unset($suit_info['eticketsmstemplet']);
        unset($suit_info['lastoffer']);
        unset($suit_info['create_type']);
        unset($suit_info['interface_code']);
        unset($suit_info['settlement_type']);
        unset($suit_info['supplier_channel_id']);
        unset($suit_info['fill_tourer_items']);

        return $suit_info;
    }

    /**
     * 热门产品
     * @param $params
     * @return array
     */
    public function hot_products($params = array())
    {
        $pagesize      = Arr::get($params, 'pagesize', 10);
        $page          = Arr::get($params, 'page', 1);
        $search_params = array(
            'page' => $page,
        );

        $plugins  = DB::select('id', 'pinyin')
            ->from('model')
            ->where("id IN (5,1,2,3,13,21,114,118,121)")
            ->order_by(DB::expr("FIND_IN_SET(id, '5,1,2,3,13,21,114,118,121')"))
            ->execute()
            ->as_array();
        $spot_num = $pagesize - count($plugins) + 1;
        $data     = array();
        foreach ($plugins as $k => $v) {
            if (!St_Functions::is_normal_app_install('system_' . $v['pinyin'])) {
                unset($plugins[$k]);
                continue;
            }
            if ($v['id'] == 5) {
                $search_params['pagesize'] = $spot_num;
            } else {
                $search_params['pagesize'] = 1;
            }
            $type_id = array();
            for ($i = 0; $i < $search_params['pagesize']; $i++) {
                array_push($type_id, $v['id']);
            }

            $offset = St_Page::offset($search_params['page'], $search_params['pagesize']);

            $tag  = Taglib_ . ucfirst($v['pinyin']);
            $list = $tag::query(array('flag' => 'order', 'row' => $search_params['pagesize'], 'offset' => $offset, 'platform' => $params['platform_no']));

            foreach ($list as &$pro) {
                $pro['type_id'] = $v['id'];
                $pro['litpic']  = $this->img_url($pro['litpic']);
            }
            $data = array_merge($data, $list);
        }

        $search_params['platform_no'] = $params['platform_no'];
        if (count($data) < $pagesize) {
            $search_params['pagesize'] = $pagesize - count($data);
            $search_params['page']     = $search_params['page'] + 1;
            $spot                      = Model_Api_V2_Spot::search($search_params);
            $spot_list                 = array_map(function ($item) {
                $item['type_id'] = 5;
                return $item;
            }, $spot['list']);
            $data                      = array_merge($data, $spot_list);
        }
        shuffle($data);

        return $data;
    }

    /**
     * 预订日历
     * @param $request_params
     * @return array
     * @throws Exception
     */
    public function book_calendar($request_params)
    {
        /**
         * @var $rows
         * @var $year
         * @var $month
         * @var $suit_id
         * @var $mid
         */
        extract($request_params);

        $is_seckill  = Arr::get($request_params, 'is_seckill', 0);
        $together_id = Arr::get($request_params, 'together_id', 0);

        $ticket_info = Model_Spot_Ticket::get_on_sale_ticket(array('ticket_id' => $suit_id));
        if (!$ticket_info) {
            throw new Exception('套餐不存在');
        }

        $spot_id = $ticket_info['spotid'];
        // 检查景点预订模式
        $spot = DB::select()
            ->from('spot')
            ->where('id', '=', $spot_id)
            ->execute()
            ->current();
        if (!$spot) {
            throw new Exception('景点不存在');
        }

        if ($together_id) {
            $together = Model_Api_V2_Together::check_together_booking($together_id, $mid);

            $spot['is_open_multiple_ticket'] = 0; // 拼团关闭多套餐预订
            $request_params['sku_id']        = $together['sku_id'];

            $price = Model_Api_V2_Spot::get_calendar_price($spot, $ticket_info, $request_params);
            // 拼团验证
            $params_data = array(
                'prices'    => $price,
                'suit_info' => $ticket_info,
                'member_id' => $mid
            );
            $price       = Model_Together_Product::get_booking_price_data($together, $params_data);
        } elseif ($is_seckill) {
            $price       = Model_Seckill_Product::get_booking_price_data($is_seckill);
        } else {
            $price = Model_Api_V2_Spot::get_calendar_price($spot, $ticket_info, $request_params);
        }

        return $price;

    }

    /**
     * 预订套餐
     * @param $request_params
     * @return array
     * @throws Exception
     */
    public function book_suit($request_params)
    {
        /**
         * @var $date
         * @var $spot_id
         */
        extract($request_params);

        if(strtotime($date) < strtotime(date("Y-m-d"))){
            throw new Exception('不能预订当日以前的日期');
        }

        $spot = DB::select()
            ->from('spot')
            ->where('id', '=', $spot_id)
            ->execute()
            ->current();
        if (!$spot) {
            throw new Exception('景点不存在');
        }

        // 拼团检查
        if ($together_id) {
            $together = Model_Api_V2_Together::check_together_booking($together_id, $mid);
            $spot['is_open_multiple_ticket'] = 0; // 拼团关闭多套餐预订
        }

        $suit_id = Arr::get($request_params, 'suit_id', '');
        if ($suit_id) {
            $ticket_info = Model_Spot_Ticket::get_on_sale_ticket(array('spot_id' => $spot_id, 'ticket_id' => $suit_id));
            if (!$ticket_info) {
                throw new Exception('套餐不存在');
            }
        }

        $result = Service_Api_Spot_Booking_Factory::get_instance($spot)->get_book_suit($request_params, $ticket_info);
        if (!empty($result['prices'])) {

            foreach ($result['prices'] as &$price) {
                $ticket_info                          = $price['ticket_info'];
                $price['people_rule']                 = Model_Spot_Ticket_People_Rule::get_ticket_people_rule($ticket_info['id']);
                $price['fill_tourer_type']            = $ticket_info['fill_tourer_type'];
                $price['fill_tourer_credential_type'] = $ticket_info['fill_tourer_credential_type'];
                unset($price['ticket_info']);
            }

            // 拼团价格处理
            if ($together_id) {
                $result['prices'] = $this->make_together_book_suit($together, $result['prices'], $ticket_info, $mid);
            }

            if ($is_seckill) {
                $result['prices'] = Model_Seckill_Product::get_seckill_price($result['prices'],$is_seckill);
            }
        }
        return $result;
    }

    /**
     * 预订拼团套餐处理
     * @param $together
     * @param $prices
     * @param $ticket_info
     * @param $mid
     * @return mixed
     * @throws Exception
     */
    private function make_together_book_suit($together, $prices, $ticket_info, $mid = '')
    {
        foreach ($prices as &$price) {
            $price['adultprice'] = $price['price'];
            $price['number'] = $price['stock'];
        }

        $params_data = array(
            'prices' =>$prices,
            'suit_info' => $ticket_info,
            'member_id' => $mid
        );
        $prices = Model_Together_Product::get_booking_price_data($together, $params_data);

        foreach ($prices as &$price) {
            $price['price'] = $price['adultprice'];
            $price['stock'] = $price['number'];
            unset($price['adultprice']);
            unset($price['number']);
        }
        return $prices;
    }

    /**
     * 预订套餐规格
     * @param $request_params
     * @return array
     * @throws Exception
     */
    public function book_sku($request_params)
    {
        $ticket_id   = Arr::get($request_params, 'suit_id');
        $date        = Arr::get($request_params, 'date');
        $together_id = Arr::get($request_params, 'together_id', '');
        $mid         = Arr::get($request_params, 'mic', '');

        if ($ticket_id) {
            $ticket_info = Model_Spot_Ticket::get_on_sale_ticket(array('ticket_id' => $ticket_id));
            if (!$ticket_info) {
                throw new Exception('套餐不存在');
            }
        }

        $spot_id    = $ticket_info['spotid'];
        $sku_params = array('ticket_id' => $ticket_id);

        // 拼团检查
        if ($together_id) {
            $together = Model_Api_V2_Together::check_together_booking($together_id, $mid);
            if ($together['sku_id']) {
                $sku_params['sku_id'] = array($ticket_id => array($together['sku_id']));
            }
        }

        $skus        = Model_Spot_Ticket_Sku::get_price_sku($spot_id, $sku_params);
        $period_time = array();
        if (!empty($skus)) {
            if (count($skus) > 1 || $skus[0]['sku_id'] != 0) {
                // 按规格报价
                foreach ($skus as $key => $sku) {
                    $price_params            = $sku;
                    $price_params['date']    = $date;
                    $price_params['is_open'] = 1;
                    $price                   = Model_Spot_Ticket_Price::get_price($price_params);
                    if (empty($price)) {
                        unset($skus[$key]);
                        continue;
                    }
                    $stock = $price['number'];
                    if($stock <= 0){
                        unset($skus[$key]);
                        continue;
                    }
                    $period_time[] = array(
                        'id' => $sku['period_time_id'],
                        'name' => Model_Spot_Period_Time::get_name_by_id($sku['period_time_id']),
                        'stock' => $stock
                    );
                }
            }
        }

        return array(
            'period_time' => $period_time
        );
    }
}